//
//  SignViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/12/22.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "SignViewController.h"
#import "ClipBoundsTableViewCell.h"
#import "SingUPViewViewController.h"

#define cellWidth kScreenW - 30
#define awardRuler @"每日登陆心情签到，获得1积分，每人每天最多一次。\n积分的目的：为了解锁更多的功能，有更多的体验项目，还可以参加组织的活动。"
@interface SignViewController ()
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,copy) NSString *mouthCount;
@property (nonatomic,copy) NSString *mood_id;
@property (nonatomic,weak) UIButton *signButton;
@property (nonatomic,assign) BOOL isSending;
@end

@implementation SignViewController
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, -20,kScreenW, kScreenH)];
    imageView.image=[UIImage imageNamed:@"sign_bg"];
    self.tableView.backgroundView = imageView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.title = @"心情签到";
    self.isSending = NO;
    
    [self creatDataList];
    [self creatHeadView];
}
#pragma mark - creatHeadView
- (void)creatHeadView{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 150)];
    headView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = headView;
    
    double buttonWidth = 80;
    UIButton *signButton = [[UIButton alloc]init];
    signButton.frame = CGRectMake( (kScreenW - buttonWidth)/2, 30, buttonWidth, buttonWidth);
    [signButton setImage:[UIImage imageNamed:@"sign_unsign"] forState:UIControlStateNormal];
    [signButton addTarget:self action:@selector(signUp) forControlEvents:UIControlEventTouchUpInside];
    self.signButton = signButton;
    [headView addSubview:signButton];
}
#pragma mark - 签到
- (void)signUp{
    if (self.isSending) {
        return;
    }
    self.isSending = YES;
    SingUPViewViewController *signUPVC = [[SingUPViewViewController alloc]init];
    signUPVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    __weak typeof (self)unself = self;
    BOOL isSign = YES;
    signUPVC.selectMoodBlock=^(NSString *moodStr){
        if (isSign) {
            YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
            [dic setValue:moodStr forKey:@"moodId"];
            [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppSignAddSign] andParmas:dic andComplition:^(id response, BOOL isuccess) {
                if (isuccess) {
                    [Global showActivityWithView:self.view withText:@"签到成功"];
                    
                    [unself creatDataList];
                }
                self.isSending = NO;
            }];
        }
        
    };
    [self presentViewController:signUPVC animated:YES completion:^{
        MyLog(@"进页面");
    }];
   
    

}
#pragma mark - creatDataList
- (void)creatDataList{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppSignGetSingLog] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:[NSMutableArray arrayWithArray:response[@"thisMouthList"]]];
            self.mood_id = [NSString stringWithFormat:@"%@",response[@"mood_id"]];
            
            self.mouthCount = [NSString stringWithFormat:@"%@",response[@"mouthCount"]];
            NSString *signHis = [NSString stringWithFormat:@"%@",response[@"sing_history"]];
            if (![signHis isEqualToString:@"0"]) {
                [self.signButton setImage:[UIImage imageNamed:@"sign_sign"] forState:UIControlStateNormal];
                self.signButton.userInteractionEnabled = NO;
            }
            
            NSInteger firstDayOfMonthInt= [self getCurrentMonthWeek];
            NSInteger count = (firstDayOfMonthInt-1)%7;
            for (int i = 0; i < count; i ++) {
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                [dic setValue:@"" forKey:@"add_time"];
                [self.dataArray insertObject:dic atIndex:0];
            }
            
            
            MyLog(@"%ld",(long)firstDayOfMonthInt);
            
            [self.tableView reloadData];
        }
    }];
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section) {
        ClipBoundsTableViewCell *cell = [[ClipBoundsTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell1"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.frame = CGRectMake(15, 10, cellWidth, 120);
        cell.backgroundColor = [UIColor whiteColor];
        
        
        UIButton *awardButton = [[UIButton alloc]init];
        awardButton.frame = CGRectMake((cellWidth - 100)/2, 10, 100, 20);
        [awardButton setImage:[UIImage imageNamed:@"sign_award"] forState:UIControlStateNormal];
        [awardButton setTitle:@" 规则与奖励" forState:UIControlStateNormal];
        [awardButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        awardButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [cell.contentView addSubview:awardButton];
        
        UIView *sepView = [[UIView alloc]initWithFrame:CGRectMake(0, 40, cellWidth, 2)];
        sepView.backgroundColor = KBACKGROUNDCOLOR;
        [cell.contentView addSubview:sepView];
        
        UILabel *desLabel = [[UILabel alloc]init];
        desLabel.text = awardRuler;
        desLabel.frame = CGRectMake(10, 50, cellWidth - 20, [Global getSizeOfString:desLabel.text maxWidth:cellWidth - 20 maxHeight:MAXFLOAT withFontSize:14].height);
        desLabel.font = [UIFont systemFontOfSize:14];
        desLabel.numberOfLines = 0;
        [cell.contentView addSubview:desLabel];
        return cell;
    }
    ClipBoundsTableViewCell *cell = [[ClipBoundsTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.frame = CGRectMake(15, 10, cellWidth, 100);
    cell.backgroundColor = [UIColor whiteColor];
    cell.clipsToBounds = YES;
    cell.layer.cornerRadius = 10;
    
    if (self.dataArray.count) {
       UILabel *dateLabel = [[UILabel alloc]init];
       dateLabel.frame = CGRectMake(0, 0, kScreenW - 20, 44);
        dateLabel.text = [NSString stringWithFormat:@"%@年%@月",[self.dataArray[8][@"add_time"] substringToIndex:4],[self.dataArray[8][@"add_time"] substringWithRange:NSMakeRange(5,2)]];
       dateLabel.textColor = [UIColor whiteColor];
       dateLabel.font = [UIFont systemFontOfSize:18];
       dateLabel.textAlignment = NSTextAlignmentCenter;
       dateLabel.backgroundColor = [UIColor orangeColor];
       [cell.contentView addSubview:dateLabel];
       
       UILabel *dayTextlabel = [[UILabel alloc]init];
       dayTextlabel.frame = CGRectMake((cellWidth - 120)/2, CGRectGetMaxY(dateLabel.frame) + 20, 90, 20);
       dayTextlabel.font = [UIFont systemFontOfSize:16];
       dayTextlabel.text = @"本月已签到";
       dayTextlabel.textAlignment = NSTextAlignmentCenter;
       dayTextlabel.textColor = RGBColor(71, 39, 17);
       [cell.contentView addSubview:dayTextlabel];
        
        UILabel *dayLabel = [[UILabel alloc]init];
        dayLabel.frame = CGRectMake(CGRectGetMaxX(dayTextlabel.frame), CGRectGetMinY(dayTextlabel.frame)- 10, 30, 30);
        dayLabel.backgroundColor = [UIColor orangeColor];
        dayLabel.clipsToBounds = YES;
        dayLabel.layer.cornerRadius = 15;
        dayLabel.text = self.mouthCount;
        dayLabel.textColor = [UIColor whiteColor];
        dayLabel.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:dayLabel];
        
        UILabel *dayTestlabel = [[UILabel alloc]init];
        dayTestlabel.frame = CGRectMake(CGRectGetMaxX(dayLabel.frame), CGRectGetMaxY(dateLabel.frame) + 20, 20, 20);
        dayTestlabel.font = [UIFont systemFontOfSize:16];
        dayTestlabel.text = @"天";
        dayTestlabel.textAlignment = NSTextAlignmentCenter;
        dayTestlabel.textColor = RGBColor(71, 39, 17);
        [cell.contentView addSubview:dayTestlabel];
    }
    
    double dayWidth = 20;
    double dayWidthMargin = (cellWidth -dayWidth*7)/8;
    double dayHighMargin = 15;
    NSArray *weekArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    for (int i = 0; i < 7; i ++) {
        UILabel *label = [[UILabel alloc]init];
        label.frame = CGRectMake( dayWidthMargin + (dayWidth + dayWidthMargin)*(i%7),80 + dayWidth + dayHighMargin, dayWidth, dayWidth);
        label.backgroundColor = [UIColor clearColor];
        label.textColor = KTEXTMAINCOLOR;
        label.clipsToBounds = YES;
        label.layer.cornerRadius = 10;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        label.text = weekArray[i];
        [cell.contentView addSubview:label];
    }
    
    for (int i = 0; i < self.dataArray.count; i ++) {
        UILabel *label = [[UILabel alloc]init];
        label.frame = CGRectMake( (kScreenW - (dayWidth+dayWidthMargin)*7)/2 + (dayWidth + dayWidthMargin)*(i%7),145 + (dayWidth + dayHighMargin)*(i/7) , dayWidth, dayWidth);
        if (![self.dataArray[i][@"add_time"] isEqualToString:@""]) {
            NSString *dayStr = [NSString stringWithFormat:@"%@",[self.dataArray[i][@"add_time"] substringFromIndex:8]];
            if ([[dayStr substringToIndex:1] isEqualToString:@"0"]) {
                dayStr = [dayStr substringFromIndex:1];
            }
            label.text = [NSString stringWithFormat:@"%@",dayStr];
        }
        NSString *moodStr = [NSString stringWithFormat:@"%@",self.dataArray[i][@"mood_id"]];
        if ([moodStr isEqualToString:@"1"]) {
            label.backgroundColor = [UIColor redColor];
            label.textColor = [UIColor whiteColor];
        }else if ([moodStr isEqualToString:@"2"]) {
            label.backgroundColor = [UIColor blackColor];
            label.textColor = [UIColor whiteColor];
        }else if ([moodStr isEqualToString:@"3"]) {
            label.backgroundColor = [UIColor blueColor];
            label.textColor = [UIColor whiteColor];
        }else if ([moodStr isEqualToString:@"4"]) {
            label.backgroundColor = KBACKNAVIGATIONCOLOR;
            label.textColor = [UIColor whiteColor];
        }else{
            label.backgroundColor = [UIColor clearColor];
            label.textColor = KTEXTMAINCOLOR;
        }
        label.clipsToBounds = YES;
        label.layer.cornerRadius = 10;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        [cell.contentView addSubview:label];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!indexPath.section) {
        return 320;
    }
    
    return [Global getSizeOfString:awardRuler maxWidth:cellWidth - 20 maxHeight:MAXFLOAT withFontSize:14].height + 60;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenW, 10);
    view.backgroundColor = [UIColor clearColor];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.01f;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)getCurrentMonthWeek{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];

    NSDate *currentdate=[NSDate date];
    NSMutableString *lacalStr= [NSMutableString stringWithFormat:@"%@",[formatter stringFromDate:currentdate]];
    lacalStr = [NSMutableString stringWithFormat:@"%@01%@",[lacalStr substringToIndex:8],[lacalStr substringFromIndex:10]];
    NSDate *date=[formatter dateFromString:lacalStr];
    
    NSCalendar *calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *comps = [calendar components:NSCalendarUnitWeekday fromDate:date];
    
    NSInteger weekday = [comps weekday];
    return weekday;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
